package com.ai.sml.util.exchange;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.channels.FileLock;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

import com.ai.sml.util.CacheUtil;
import com.ai.sml.util.DateUtil;
import com.ai.sml.util.StringUtil;

/**
 * 在redis上进行兑换操作。
 * @author litianxiang
 */
public class ExchangeOnRedisUtil {
	private static File file = new File("src/main/resources/exchange.txt") ;
	private static BufferedReader br = null ;
	private static PrintWriter pw = null ;
	private static final Logger LOGGER = Logger.getLogger("UTIL");
	
	
	/**
	 * 读取文件到redis。
	 */
	public static void readFileToRedis(){
		LOGGER.info("readFileToRedis Start-->");
		try {
			CacheUtil.put2Cache(getKeyFromFile(), getMapFromFile().toString(), 2592000);	//30天
		} catch (Exception e) {
			LOGGER.error(e.getMessage(),e);
			e.printStackTrace();
		}
		LOGGER.info("readFileToRedis End-->");
	}
	
	/**
	 * 根据手机号返回资源编号
	 * @param telnum
	 */
	public static String exchangeInfoByTelnum(String telnum){
		LOGGER.info("exchangeInfoByTelnum Start-->");
		String info = null ;
		if(StringUtil.isNotEmpty(telnum)){
			String value = stringToMap(CacheUtil.getFromCache(getKeyFromFile())).get(telnum);
			if (StringUtil.isNotEmpty(value)) {
				String[] temp = value.split("\\|");
				if("0".equals(temp[2])){
					info = value.split("\\|")[1];
				}
			}
		}
		LOGGER.info("exchangeInfoByTelnum End-->");
		return info ;
	}
	
	/**
	 * 根据手机号修改缓存
	 * @param loginTelnum		登录手机号
	 * @param exchangeTelnum	兑换手机号
	 */
	public synchronized static void updateRedisByTelnum(String loginTelnum,String exchangeTelnum){
		LOGGER.info("updateRedisByTelnum Start-->");
		if(StringUtil.isNotEmpty(loginTelnum) && StringUtil.isNotEmpty(exchangeTelnum)){
			String key = getKeyFromFile() ;
			Map<String,String> map = stringToMap(CacheUtil.getFromCache(key));
			String[] value = map.get(loginTelnum).split("\\|");
			value[2] = "1";
			value[3] = DateUtil.date2String(new Date(),DateUtil.DATE_PATTERN.YYYYMMDDHHMMSS);
			value[4] = exchangeTelnum;
			map.put(loginTelnum, arrayToString(value));
			CacheUtil.put2Cache(key, map.toString(), 2592000);					//30天
			writeFileFromRedis(key,map);
		}
		LOGGER.info("updateRedisByTelnum End -->");
	}
	
	/**
	 * 缓存数据写入文件，执行同步
	 */
	public static void writeFileFromRedis(String key,Map<String, String> map){
		LOGGER.info("writeFileFromRedis Start -->");
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			FileLock lock = fos.getChannel().tryLock();				//文件加锁
			pw = new PrintWriter(new OutputStreamWriter(fos),true);
			pw.println("##"+key);
			for (Map.Entry<String, String> entry : map.entrySet()) {
				pw.println(entry.getValue());
			}
			if(lock!=null){
				lock.release();										//文件解锁
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage(),e);
			e.printStackTrace();
		} finally {
			try {
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
				LOGGER.error(e.getMessage(),e);
				e.printStackTrace();
			}
		}
		LOGGER.info("writeFileFromRedis End -->");
	}
	
	/**
	 * 从文件中获取key
	 * @return
	 */
	public static String getKeyFromFile(){
		String key = null ;
		try (FileInputStream fis = new FileInputStream(file);InputStreamReader read = new InputStreamReader(fis);){
			br = new BufferedReader(read);
			String str = null ;
			if(null != (str = br.readLine())){
				if(str.startsWith("##")){
					key = str.substring(2);
				}
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage(),e);
			e.printStackTrace();
		} finally {
			try {
				if(br!=null){
					br.close();
				}
			} catch (IOException e) {
				LOGGER.error(e.getMessage(),e);
				e.printStackTrace();
			}
		}
		return key ;
	}

	/**
	 * 从文件中获取map
	 * @return
	 */
	public static Map<String, String> getMapFromFile(){
		Map<String, String> map = null;
		try (FileInputStream fis = new FileInputStream(file);InputStreamReader read = new InputStreamReader(fis);){
			br = new BufferedReader(read);
			String str = null ;
			map = new HashMap<String, String>() ;
			while(null != (str = br.readLine())){
				if(!str.startsWith("#")){
					String[] temp = str.split("\\|");
					map.put(temp[0], str);
				}
			}
		} catch (Exception e) {
			LOGGER.error(e.getMessage(),e);
			e.printStackTrace();
		} finally {
			try {
				if(br!=null){
					br.close();
				}
			} catch (IOException e) {
				LOGGER.error(e.getMessage(),e);
				e.printStackTrace();
			}
		}
		return map ;
	}
	
	/**
	 * 字符串转成map
	 * @param string
	 * @return map
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, String> stringToMap(String string){
		Map<String,String> map = null ;
		if (StringUtil.isNotEmpty(string)) {
			JSONObject jsonObject = JSONObject.fromObject(string);
			map = (Map<String,String>)jsonObject;
		}
		return map ;
	}
	
	/**
	 * 将数组转成字符串，以“|”分割。
	 * @param strings 数组
	 * @return 返回字符串
	 */
	public static String arrayToString(String[] strings){
		StringBuilder sb = new StringBuilder() ;
		String string;
		if (strings.length > 0) {
			for (int i = 0; i < strings.length; i++) {
				sb.append(strings[i]).append("|");
			}
		}
		string = sb.toString();
		return string.substring(0,string.length()-1) ;
	}
	
}